module Api
  class DemandController < ApplicationController
    include Apiable

    def index
      demands = Demand.select(:id, :title, :status, :created_at, :creator_id).
                      where(status: DEMAND_TYPE["未完成"]).
                      page(params[:page]).
                      per(params[:page_size])

      data! demands.as_json(only: [:id, :title, :status, :created_at],
          include: {
            creator: {
              only: [
                :id,
                :nickname,
                :location,
                :longitude,
                :latitude,
                :distance_to_me,
                :post,
                :done,
                :positive,
                :neutral,
                :negative
              ]
            }
          })
    end

    def show
      demand = Demand.select(:id, :title, :description, :status, :created_at, :creator_id).
                      find_by(id: params[:id])

      data! demand.as_json(only: [:id, :title, :description, :status, :created_at],
          include: {
            creator: {
              only: [
                :id,
                :nickname,
                :location,
                :longitude,
                :latitude,
                :distance_to_me,
                :post,
                :done,
                :positive,
                :neutral,
                :negative
              ]
            },
            messages: {
              only: [ :content, :created_at, :demand_id ],
              include: {
                sender: { only: [:id, :name] },
                receiver: { only: [:id, :name] }
              }
            },
            images: { only: [ :id, :url ] }
          })
    end

    def new
      params[:creator_id] = api_current_user.id
      if Demand.create_with_images(params)
        data!
      else
        error! "新建失败"
      end
    end
  end
end